package com.yunji.framework_template.biz.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yunji.framework_template.biz.cache.CacheService;
import com.yunji.framework_template.common.web.Page;
import com.yunji.framework_template.orm.persistence.mapper.GameMapper;
import com.yunji.framework_template.orm.persistence.model.Game;

/**
 * Created by fenglibin on 2018/12/12.
 */
@Service
public class GameService {

    @Autowired
    private GameMapper   gameMapper;
    @Resource
    private CacheService cacheService;

    public int deleteByPrimaryKey(Integer id) {
        return gameMapper.deleteByPrimaryKey(id);
    }

    public int insert(Game record) {
        return gameMapper.insert(record);
    }

    public int insertSelective(Game record) {
        return gameMapper.insertSelective(record);
    }

    public Game selectByPrimaryKey(Integer id) {
        Game game = cacheService.getCountryCache().getGames().get(id);
        if (game == null) {
            game = gameMapper.selectByPrimaryKey(id);
        }
        return game;
    }

    public int updateByPrimaryKeySelective(Game record) {
        return gameMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(Game record) {
        return gameMapper.updateByPrimaryKey(record);
    }

    public int updateTimesByPrimaryKey(Game record) {
        return gameMapper.updateTimesByPrimaryKey(record);
    }

    public List<Game> selectByCondition(Game record) {
        return gameMapper.selectByCondition(record);
    }

    public List<Game> selectAll() {
        return gameMapper.selectAll();
    }

    public List<Game> selectByPage(Page<Game> page) {
        return gameMapper.selectByPage(page);
    }

    public Integer count(Game record) {
        return gameMapper.count(record);
    }

    public int deleteByCondition(Game record) {
        return gameMapper.deleteByCondition(record);
    }

    /**
     * 随机返回几个游戏
     * 
     * @return
     */
    public List<Game> getRandomGames() {
        List<Game> gameList = new ArrayList<Game>();
        Map<Integer, List<Game>> pageGame = cacheService.getCountryCache().getPageGame();
        for (int index = 1; index <= 2; index++) {
            List<Game> list = pageGame.get(index);
            Set<Integer> seeds = new HashSet<Integer>();
            for (int num = 0; num < 4; num++) {
                int randomIndex = (int) (Math.random() * list.size());
                if (!seeds.contains(randomIndex)) {
                    gameList.add(list.get(randomIndex));
                    seeds.add(randomIndex);
                }
            }
        }
        return gameList;
    }

}
